<?php

use Biz\model\brandActivity\BlindBoxCueCard as mBlindBoxCueCard;
use Biz\service\brand\BlindBox;
use Doraemon\service\Point;
use Doraemon\tools\PointConfig;
use Hhzbeads\Point\PointClient;
use Biz\cache\brand\BrandShowActivity;

/**
 * 兑换一张提示卡
 */
class ExchangeCueCardAction extends ActionPlugin
{
    const USER_LEVEL = self::LEVEL_REGISTER;

    public function main()
    {
        if (!BrandShowActivity::isLock($this->uid . '-blind-box', 2)) {
            $point = BlindBox::EXCHANGE_CUE_CARD_POINT;
            $currPoint = Point::getPoint($this->uid);
            if ($currPoint < $point) {
                throw new \Exception('积分不足');
            }
            $start = date('Y-m-d');
            $end = date('Y-m-d H:i:s', strtotime($start) + 86399);
//            $todayExchangeCount = mBlindBoxCueCard::selectCountWhere(['uid' => $this->uid, 'addtime[>=]' => $start, 'addtime[<=]' => $end]);
//            if ($todayExchangeCount >= BlindBox::USER_EVERY_DAY_EXCHANGE_CUE_CARD) {
//                throw new \Exception('今日提示卡兑换额度已用完');
//            }
            $expireTime = date('Y-m-d', strtotime("+30 days"));
            $expireTime = date('Y-m-d H:i:s', strtotime($expireTime) - 1);
            $cardId = mBlindBoxCueCard::insertData(['uid' => $this->uid, 'card_type' => mBlindBoxCueCard::CARD_TYPE_EXCLUDE,
                'from_source' => mBlindBoxCueCard::CARD_FROM_SOURCE_POINT, 'expire_time' => $expireTime
            ]);
            if (!$cardId) {
                throw  new \Exception('兑换提示卡失败');
            }
            $request_id = $this->uid . '-' . $cardId . '-' . date('Ymd') . '-' . PointConfig::POINT_TYPE_BLIND_BOX_EXCHANGE_CUE_CARD;
            //扣除积分
            PointClient::deductPoint($this->uid, $point, PointConfig::POINT_TYPE_BLIND_BOX_EXCHANGE_CUE_CARD, $request_id, 'community', json_encode(['card_id' => $cardId]));
        } else {
            throw new \Exception('你的操作太频繁');
        }
        $this->setSuccess();
    }
}